﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using intelliSys.NankaiUtilities.EventSynchronizer;
using System.Xml.Serialization;
using System.IO;

namespace intelliSys.NankaiUtilities.EventSynchronizer.EventProbing
{
    public class NKUEventProber
    {
        public static Dictionary<int, int> ProbingState;
        public static bool DetectEvents()
        {
            return true;
            var eventSources = EventSourceProber.Probe();
            Dictionary<int, int> currentProbingState = new Dictionary<int, int>();
            bool detectedNewEvent = false;
            TryLoadProbingState();
            foreach (var eventSource in eventSources)
            {
                currentProbingState.Add(eventSource.Description.GetHashCode(), eventSource.GenerateEventList().Count);
                if (ProbingState.ContainsKey(eventSource.Description.GetHashCode()) && (ProbingState[eventSource.Description.GetHashCode()] < currentProbingState[eventSource.Description.GetHashCode()]))
                {
                    detectedNewEvent = true;
                }
                if (ProbingState.ContainsKey(eventSource.Description.GetHashCode()) == false)
                {
                    detectedNewEvent = true;
                }
            }
            if (detectedNewEvent)
            {
                ProbingState = currentProbingState;
                SaveProbingState();
            }
            return detectedNewEvent;
        }

        public static void SaveProbingState()
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Dictionary<int, int>));
            Stream stream;
            try
            {
                using (stream = File.Open("nkuLiveSyncProbingState", FileMode.OpenOrCreate))
                {
                    xmlSerializer.Serialize(stream, ProbingState);
                }
            }
            catch
            {
                ProbingState = new Dictionary<int, int>();
            }
        }

        public static void TryLoadProbingState()
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Dictionary<int, int>));
            Stream stream;
            try
            {
                using (stream = File.Open("nkuLiveSyncProbingState", FileMode.OpenOrCreate))
                {
                    ProbingState = xmlSerializer.Deserialize(stream) as Dictionary<int, int>;
                }
            }
            catch
            {
                ProbingState = new Dictionary<int, int>();
            }
        }

    }
}
